package com.utils.catche;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.Cache;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component("wdlsCacheManager")
public class CacheManager implements org.springframework.cache.CacheManager{

    private Map<String, Cache> caches = new HashMap<String, Cache>();

    private Cache redisCache;

    private Cache ehcacheCache;

    private Cache servletCache;

    @Autowired(required = false)
    @Qualifier("ehcacheCache")
    public void setEhcacheCache(Cache ehcacheCache) {
        this.ehcacheCache = ehcacheCache;
    }

    @Autowired(required = false)
    @Qualifier("servletCache")
    public void setServletCache(Cache servletCache) {
        this.servletCache = servletCache;
    }

    @Autowired(required = false)
    @Qualifier("redisCache")
    public void setRedisCache(Cache redisCache) {
        this.redisCache = redisCache;
    }

    public void setCaches(Collection<Cache> cs) {
        if (cs != null) {
            for (Cache c : cs) {
                caches.put(c.getName(), c);
            }
        }
    }

    @PostConstruct
    public void init(){
        if(ehcacheCache!=null){
            caches.put(ehcacheCache.getName(), ehcacheCache);
        }
        if(redisCache!=null){
            caches.put(redisCache.getName(), redisCache);
        }
        if(servletCache!=null){
            caches.put(servletCache.getName(), servletCache);
        }
    }

    @Override
    public Cache getCache(String name) {
        return caches.get(name);
    }

    @Override
    public Collection<String> getCacheNames() {
        return caches.keySet();
    }

}

